package top.boycharse.ftp.server;

import top.boycharse.ftp.server.common.ThreadPoolManager;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class Server {

    private static Server server;

    private ServerSocket serverSocket;

    private static boolean isStop = false;

    private Map<Long,ServerFTPProcess> connectionInfo;

    private Server(int port) throws Exception{
        serverSocket = new ServerSocket(port);
        connectionInfo = new HashMap<>();
    }

    public static void start(int port) throws Exception {
        if (server == null) {
            server = new Server(port);
        }

            System.out.println("服务器启动");
            // 开启服务器
            while (true) {
                if (isStop) {
                    break;
                }
                Socket socket = null;
                try {
                    if (server.serverSocket != null) {
                        socket = server.serverSocket.accept();
                        System.out.println(socket.getInetAddress().getHostAddress() + "已连接");
                        long id = System.currentTimeMillis();
                        ServerFTPProcess process = new ServerFTPProcess(socket,id) {
                            @Override
                            public void destroy() {
                                // 销毁时从map中移除
                                server.connectionInfo.remove(getId());
                            }
                        };
                        server.connectionInfo.put(id,process);
                        process.start();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


    }

    public static void stop() {
        isStop = true;
    }
}
